<template>
  <div class="container">
    <h1 class="title">基金经理列表</h1>

    <!-- 筛选区域 -->
    <el-row class="filters" gutter="12" align="middle">
      <el-col :xs="24" :sm="8">
        <el-select
            v-model="selectedTags"
            multiple
            collapse-tags
            collapse-tags-tooltip
            placeholder="选择标签"
            clearable
            style="width: 100%;"
        >
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.name" />
        </el-select>
      </el-col>

      <el-col :xs="24" :sm="8">
        <el-input
            v-model="keyword"
            placeholder="输入基金经理姓名"
            clearable
            style="width: 100%;"
        />
      </el-col>

      <el-col :xs="12" :sm="4">
        <el-button type="primary" @click="searchManagers" style="width: 100%;">
          <el-icon><Search /></el-icon>搜索
        </el-button>
      </el-col>

      <el-col :xs="12" :sm="4">
        <el-button @click="resetFilters" style="width: 100%;">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-col>
    </el-row>

    <p style="margin-top: 12px;">共 {{ total }} 位基金经理</p>

    <el-alert
        v-if="selectedFunds.length > 0"
        type="info"
        show-icon
        :title="`已选中 ${selectedFunds.length} 只基金`"
        style="margin-bottom: 12px;"
    />

    <!-- 基金经理表格 -->
    <el-table
        :data="managers"
        row-key="id"
        border
        style="width: 100%;"
        :expand-row-keys="expandedRows"
        @expand-change="loadManagerFunds"
    >
      <el-table-column type="expand">
        <template #default="props">
          <el-table
              :ref="el => fundTableRefs[props.row.id] = el"
              :data="props.row.funds || []"
              border
              size="small"
              :row-key="fund => fund.code"
              @selection-change="selection => handleSelectionChange(selection, props.row)"
          >
            <el-table-column type="selection" width="50" />
            <el-table-column prop="code" label="基金代码" width="120" />
            <el-table-column prop="name" label="基金名称" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="companyName" label="基金公司" />
            <el-table-column prop="latestNav" label="最新净值" />
            <el-table-column prop="latestNavDate" label="净值日期" />
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                    size="small"
                    type="success"
                    plain
                    @click.stop="viewProfile(scope.row.code)"
                >
                  查看画像
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>

      <el-table-column prop="name" label="基金经理" width="200" />
      <el-table-column prop="fundCount" label="管理基金数" width="150" />
      <el-table-column prop="intro" label="简介" />
    </el-table>

    <!-- 分页与操作栏 -->
    <div class="bottom-bar">
      <span class="selected-count">已选中 {{ selectedFunds.length }} 只基金</span>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
      <el-button type="success" @click="openSaveDialog">
        <el-icon><FolderAdd /></el-icon>
        保存为组合
      </el-button>
    </div>

    <!-- 保存组合弹窗复用组件 -->
    <SavePortfolioDialog
        v-model="dialogVisible"
        :fund-codes="selectedFunds"
        :user-id="userId"
        @saved="fetchManagers"
    />

    <!-- 基金画像弹窗复用组件 -->
    <FundProfileDialog
        v-model="profileVisible"
        :profile-data="profileData"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Search, Refresh, FolderAdd } from '@element-plus/icons-vue'

import SavePortfolioDialog from '@/components/SavePortfolioDialog.vue'
import FundProfileDialog from '@/components/FundProfileDialog.vue'

const managers = ref([])
const tags = ref([])
const selectedTags = ref([])
const keyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const expandedRows = ref([])
const selectedFunds = ref([])
const fundTableRefs = ref({})
const managerSelections = ref({})

const dialogVisible = ref(false)
const profileVisible = ref(false)
const profileData = ref(null)
const userId = 1

onMounted(() => {
  loadTags()
  fetchManagers()
})

const loadTags = async () => {
  const res = await axios.get('/api/tag/all')
  tags.value = res.data
}

const fetchManagers = async () => {
  const params = selectedTags.value.length > 0
      ? { tags: selectedTags.value }
      : {
        page: currentPage.value - 1,
        size: pageSize.value,
        keyword: keyword.value
      }

  const url = selectedTags.value.length > 0 ? '/api/fund-manager/by-tags' : '/api/fund-manager/page'
  const res = await axios.get(url, {
    params,
    paramsSerializer: params => {
      const searchParams = new URLSearchParams()
      for (const key in params) {
        const value = params[key]
        if (Array.isArray(value)) {
          value.forEach(v => searchParams.append(key, v))
        } else if (value !== null && value !== undefined) {
          searchParams.append(key, value)
        }
      }
      return searchParams.toString()
    }
  })

  managers.value = res.data.content || res.data
  total.value = res.data.totalElements || res.data.length
  expandedRows.value = []
}

const loadManagerFunds = async (row, expanded) => {
  if (expanded && !row.funds) {
    const res = await axios.get('/api/fund-manager/funds', {
      params: { managerName: row.name }
    })
    row.funds = res.data

    await nextTick()
    const tableRef = fundTableRefs.value[row.id]
    if (tableRef && row.funds) {
      row.funds.forEach(fund => {
        if (selectedFunds.value.includes(fund.code)) {
          tableRef.toggleRowSelection(fund, true)
        }
      })
    }
  }
}

const handleSelectionChange = (selection, managerRow) => {
  managerSelections.value[managerRow.id] = selection.map(f => f.code)
  const allSelected = Object.values(managerSelections.value).flat()
  selectedFunds.value = Array.from(new Set(allSelected))
}

const openSaveDialog = () => {
  if (selectedFunds.value.length === 0) {
    ElMessage.warning('请选择要保存的基金')
    return
  }
  dialogVisible.value = true
}

const viewProfile = async (code) => {
  try {
    const res = await axios.get(`/api/fund-profile/${code}`)
    profileData.value = res.data
    profileVisible.value = true
  } catch (err) {
    ElMessage.error('加载画像失败：' + (err.response?.data?.message || err.message))
  }
}

const searchManagers = () => {
  currentPage.value = 1
  fetchManagers()
}

const resetFilters = () => {
  keyword.value = ''
  selectedTags.value = []
  currentPage.value = 1
  selectedFunds.value = []
  managerSelections.value = {}
  fetchManagers()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchManagers()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchManagers()
}
</script>

<style scoped>
.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 40px;
}
.title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 20px;
}
.filters {
  margin-bottom: 16px;
}
.bottom-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  flex-wrap: wrap;
}
.selected-count {
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
